/**
 * 线程同步例程：说明同一个对象中的多个同步方法的运行机制
 */
package thread;

public class J_SynchronizedMethod extends Thread {
    public int m_ID;
    public J_Experiment3 m_data;

    public J_SynchronizedMethod(int id) {
        m_ID = id;
    }

    @Override
    public void run() {
        System.out.println("运行线程：" + m_ID);
        m_data.mb_method1(m_ID);
        m_data.mb_method2(m_ID);
        System.out.println("结束线程：" + m_ID);
    }

    public static void main(String args[]) {
        int n = 10;
        J_SynchronizedMethod[] t = new J_SynchronizedMethod[n];
        J_Experiment3 d = new J_Experiment3();
        for (int i = 0; i < n; i++) {
            t[i] = new J_SynchronizedMethod(i);
            t[i].m_data = d;
            t[i].start();
        }
        System.out.println("方法main结束");
    }
}

class J_Experiment3 {
    public static void mb_sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            System.out.println("异常 InterruptedException：" + e);
            e.printStackTrace();
        }
    }

    public synchronized void mb_method1(int id) {
        System.out.printf("线程 %1$d 进入同步方法1\r\n", id);
        mb_sleep(100);
        System.out.printf("线程 %1$d 离开同步方法1\r\n", id);
    }

    public synchronized void mb_method2(int id) {
        System.out.printf("线程 %1$d 进入同步方法2\r\n", id);
        mb_sleep(100);
        System.out.printf("线程 %1$d 离开同步方法2\r\n", id);
    }
}
